package com.cjjd.c.feature.subscribe.near_hotel;


import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.BaseFragment;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.ListResult;
import com.cjjd.c.bean.subscribe.HotelStarBean;
import com.cjjd.c.bean.subscribe.NearbyHotelShowModel;
import com.cjjd.c.feature.subscribe.info.HotelDetailActivity;
import com.cjjd.c.feature.subscribe.select_hotel.HotelStarAdapter;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.CommonUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.edmodo.rangebar.RangeBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Response;

/**
 * ----------------------------------
 * Created by xyd on 2017/11/22.
 * <p/>
 * 描  述：附近酒店
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class HotelNearFragment extends BaseFragment implements View.OnClickListener {


    @Bind(R.id.ll_tab)
    LinearLayout llTab;
    @Bind(R.id.lineview)
    View lineview;

    @Bind(R.id.cb_1)
    CheckBox cb1;
    @Bind(R.id.cb_2)
    CheckBox cb2;
    @Bind(R.id.cb_3)
    CheckBox cb3;

    @Bind(R.id.recycleview_hotel_group)
    ListView nearListView;

    private double latitude = -1;    // 纬度
    private double longitude = -1;   // 经度
    private List<NearbyHotelShowModel> listData = new ArrayList<>();

    private HotelNearAdapter hotelNearAdapter;

    // 排序选择
    private String orderByStr = "0";
    // 星级
    private List<HotelStarBean> starList;
    private HotelStarAdapter hotelStarAdapter;
    private StringBuffer starLevel = new StringBuffer("-1");
    // 筛选价格
    private String priceString = "-1";
    // 距离范围
    private String distanceStr = "-1";
    // 服务设施
    private StringBuffer serviceStr = new StringBuffer("");

    @Override
    public int getContentView() {
        return R.layout.fragment_home_near;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        initView();
        initLoaction();
        return rootView;
    }


    //<editor-fold desc="自动定位">
    private AMapLocationClient mLocationClient;


    private void initLoaction() {
        mLocationClient = new AMapLocationClient(mContext);
        AMapLocationClientOption option = new AMapLocationClientOption();
        // 默认采用连续定位模式, 设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        //option.setInterval(3000);
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 如果您需要使用单次定位 true, 该方法默认为false。
        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    Log.e("xyd", "ErrorCode = " + aMapLocation.getErrorCode());
                    Log.e("xyd", "LocationDetail = " + aMapLocation.getLocationDetail());
                    if (aMapLocation.getErrorCode() == 0) {

                        // 纬度
                        latitude = aMapLocation.getLatitude();
                        // 经度
                        longitude = aMapLocation.getLongitude();
                        getData();
                    } else {
                        //mContext.mCityAdapter.updateLocateState(666, (String) null);
                    }
                }

            }
        });
        mLocationClient.startLocation();
    }

    //</editor-fold>


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && longitude != -1 && latitude != -1) {
            getData();
        }
    }

    private void getData() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("pageNow", 1 + "");
        h1.put("pageShow", 30 + "");
        h1.put("longitude", longitude + "");   // 经度
        h1.put("latitude", latitude + "");    // 维度
        h1.put("orderBy", orderByStr);    // 推荐排序： 0推荐排序 1低价排序 2高价排序 3好评排序
        h1.put("starLevel", starLevel.toString());    //  星级： -1不限 0客栈公寓 1经济连锁 2二星 3三星  4四星 5五星
        h1.put("price", priceString);    //  价格: -1不限
        h1.put("dist", distanceStr);    //  距离范围: -1不限
        h1.put("servicer", serviceStr.toString());    //  服务设施: 用","分割传递   1停车场 2餐厅 3游泳池 4会议中心 5健身房 6无线网 7商务中心 8宽带上网 9 接机服务

        Call<HttpResult<ListResult<NearbyHotelShowModel>>> call = service.getNearbyHotelList(JsonUtils.convertParam("getNearbyHotelList", h1));
        call.enqueue(new CallbackImpl<ListResult<NearbyHotelShowModel>>() {
            @Override
            public void responseSuccess(Call<HttpResult<ListResult<NearbyHotelShowModel>>> call, Response<HttpResult<ListResult<NearbyHotelShowModel>>> response) {
                if (listData.size() > 0) {
                    listData.clear();
                }
                listData.addAll(response.body().getData().dataList);
                hotelNearAdapter.notifyDataSetChanged();
                CommonUtil.setListViewHeightBasedOnChildren(nearListView);
            }
        });
    }


    private void initView() {

        // 选中--> 展开
        // 不选中-- 关闭
        // 关闭 -- 不选中。

        cb1.setOnClickListener(this);
        cb2.setOnClickListener(this);
        cb3.setOnClickListener(this);


        hotelNearAdapter = new HotelNearAdapter(mContext);
        hotelNearAdapter.setData(listData);
        nearListView.setAdapter(hotelNearAdapter);
        CommonUtil.setListViewHeightBasedOnChildren(nearListView);
        nearListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NearbyHotelShowModel nearbyHotelShowModel = listData.get(position);
                Intent intent = new Intent(mContext, HotelDetailActivity.class);
                intent.putExtra("hotelUuid", nearbyHotelShowModel.hotelUuid);
                mContext.startActivity(intent);
            }
        });

        starList = new ArrayList<>();
        starList.add(new HotelStarBean("不限"));
        starList.add(new HotelStarBean("客栈公寓"));
        starList.add(new HotelStarBean("经济连锁"));
        starList.add(new HotelStarBean("二星其他"));
        starList.add(new HotelStarBean("三星舒适"));
        starList.add(new HotelStarBean("四星高端"));
        starList.add(new HotelStarBean("五星豪华"));

        hotelStarAdapter = new HotelStarAdapter(mContext);
        hotelStarAdapter.setData(starList);


    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    private PopupWindow popupWindow1;
    TextView tv_sort_recommend;
    TextView tv_sort_low_price;
    TextView tv_hight_price;
    TextView tv_praise;

    private void showRecommendPopwindowView() {

        if (popupWindow1 == null) {
            View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_sort, null);
            tv_sort_recommend = (TextView) contentView.findViewById(R.id.tv_sort_recommend);
            tv_sort_low_price = (TextView) contentView.findViewById(R.id.tv_sort_low_price);
            tv_hight_price = (TextView) contentView.findViewById(R.id.tv_hight_price);
            tv_praise = (TextView) contentView.findViewById(R.id.tv_praise);
            tv_sort_recommend.setOnClickListener(this);
            tv_sort_low_price.setOnClickListener(this);
            tv_hight_price.setOnClickListener(this);
            tv_praise.setOnClickListener(this);

            popupWindow1 = new PopupWindow(mContext);
            popupWindow1.setContentView(contentView);
            popupWindow1.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            popupWindow1.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            popupWindow1.setBackgroundDrawable(new BitmapDrawable());
            popupWindow1.setOutsideTouchable(true);
            popupWindow1.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    if (cb1.isChecked()) {
                        Log.e("xyd", "checkChecked is  " + cb1.isChecked());
                        cb1.setChecked(false);
                    }
                }
            });

            popupWindow1.showAsDropDown(lineview);
        } else {
            popupWindow1.showAsDropDown(lineview);
        }
    }


    private PopupWindow popupWindow2;
    private RangeBar rangebarPrice;
    private TextView tv_price_start;

    private void showStarPopwindowView() {
        if (popupWindow2 == null) {
            View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_star, null);
            tv_price_start = (TextView) contentView.findViewById(R.id.tv_price_start);
            GridView gv_star = (GridView) contentView.findViewById(R.id.gv_star);
            gv_star.setAdapter(hotelStarAdapter);

            rangebarPrice = (RangeBar) contentView.findViewById(R.id.rangebar);
            rangebarPrice.setThumbIndices(0, 0);
            rangebarPrice.setOnRangeBarChangeListener(new RangeBar.OnRangeBarChangeListener() {
                @Override
                public void onIndexChangeListener(RangeBar rangeBar, int leftThumbIndex, int rightThumbIndex) {
                    //tv_num_bar_tittle.setText(rightThumbIndex + 1 + "间");
                    tv_price_start.setText("￥" + (leftThumbIndex * 100));
                    if (rightThumbIndex > 0) {
                        priceString = (leftThumbIndex * 100) + "-" + (rightThumbIndex * 100);
                    }
                }
            });
            Button btnNegative = (Button) contentView.findViewById(R.id.btn_negative);
            btnNegative.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow2.dismiss();
                }
            });
            Button btn_positive = (Button) contentView.findViewById(R.id.btn_positive);
            btn_positive.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow2.dismiss();
                    // TODO: 2017/12/25 按照星级价格查询
                    // 获取并赋值星级
                    starLevel.delete(0, starLevel.length());
                    for (int i = 0; i < starList.size(); i++) {
                        if (starList.get(i).isSelected) {
                            starLevel.append(i - 1 + "");
                        }
                    }
                    if (starLevel.length() == 0) {
                        starLevel.append("-1");
                    }
                    getData();

                }
            });

            popupWindow2 = new PopupWindow(mContext);
            popupWindow2.setContentView(contentView);
            popupWindow2.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            popupWindow2.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            popupWindow2.setBackgroundDrawable(new BitmapDrawable());
            popupWindow2.setOutsideTouchable(true);
            popupWindow2.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    if (cb2.isChecked()) {
                        Log.e("xyd", "checkChecked is  " + cb2.isChecked());
                        cb2.setChecked(false);
                    }
                }
            });

            popupWindow2.showAsDropDown(lineview);
        } else {
            popupWindow2.showAsDropDown(lineview);
        }
    }


    private PopupWindow popupWindow3;
    private RangeBar rangebarDistance;

    private void showComprehensivePopwindowView() {

        if (popupWindow3 == null) {
            final View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_comprehensive, null);

            rangebarDistance = (RangeBar) contentView.findViewById(R.id.rangebar);
            rangebarDistance.setThumbIndices(0, 4);
            rangebarDistance.setOnRangeBarChangeListener(new RangeBar.OnRangeBarChangeListener() {
                @Override
                public void onIndexChangeListener(RangeBar rangeBar, int leftThumbIndex, int rightThumbIndex) {

                    if (rightThumbIndex == 4) {
                        distanceStr = "-1";
                    } else if (rightThumbIndex == 3) {
                        distanceStr = "10";
                    } else if (rightThumbIndex == 2) {
                        distanceStr = "5";
                    } else if (rightThumbIndex == 1) {
                        distanceStr = "3";
                    } else if (rightThumbIndex == 0) {
                        distanceStr = "1";
                    }

                }
            });
            final CheckBox checkBox1 = (CheckBox) contentView.findViewById(R.id.cb_compr_1);
            final CheckBox checkBox2 = (CheckBox) contentView.findViewById(R.id.cb_compr_2);
            final CheckBox checkBox3 = (CheckBox) contentView.findViewById(R.id.cb_compr_3);
            final CheckBox checkBox4 = (CheckBox) contentView.findViewById(R.id.cb_compr_4);
            final CheckBox checkBox5 = (CheckBox) contentView.findViewById(R.id.cb_compr_5);
            final CheckBox checkBox6 = (CheckBox) contentView.findViewById(R.id.cb_compr_6);
            final CheckBox checkBox7 = (CheckBox) contentView.findViewById(R.id.cb_compr_7);
            final CheckBox checkBox8 = (CheckBox) contentView.findViewById(R.id.cb_compr_8);
            final CheckBox checkBox9 = (CheckBox) contentView.findViewById(R.id.cb_compr_9);


            Button btn_negative_compr = (Button) contentView.findViewById(R.id.btn_negative_compr);
            Button btn_positive_compr = (Button) contentView.findViewById(R.id.btn_positive_compr);
            btn_negative_compr.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow3.dismiss();
                }
            });
            btn_positive_compr.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow3.dismiss();

                    serviceStr.delete(0, serviceStr.length());
                    if (checkBox1.isChecked()) {
                        serviceStr.append("停车场,");
                    }
                    if (checkBox2.isChecked()) {
                        serviceStr.append("餐厅,");
                    }
                    if (checkBox3.isChecked()) {
                        serviceStr.append("游泳池,");
                    }
                    if (checkBox4.isChecked()) {
                        serviceStr.append("会议中心,");
                    }
                    if (checkBox5.isChecked()) {
                        serviceStr.append("健身房,");
                    }
                    if (checkBox6.isChecked()) {
                        serviceStr.append("无线网,");
                    }
                    if (checkBox7.isChecked()) {
                        serviceStr.append("商务中心,");
                    }
                    if (checkBox8.isChecked()) {
                        serviceStr.append("宽带上网,");
                    }
                    if (checkBox9.isChecked()) {
                        serviceStr.append("接机服务,");
                    }
                    if (serviceStr.length() > 0) {
                        serviceStr.delete(serviceStr.length() - 1, serviceStr.length());
                    }

                    getData();
                }
            });


            popupWindow3 = new PopupWindow(mContext);
            popupWindow3.setContentView(contentView);
            popupWindow3.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            popupWindow3.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            popupWindow3.setBackgroundDrawable(new BitmapDrawable());
            popupWindow3.setOutsideTouchable(true);
            popupWindow3.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    if (cb3.isChecked()) {
                        Log.e("xyd", "checkChecked is  " + cb3.isChecked());
                        cb3.setChecked(false);
                    }
                }
            });

            popupWindow3.showAsDropDown(lineview);
        } else {
            popupWindow3.showAsDropDown(lineview);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.cb_1 && cb1.isChecked()) {
            if (cb2.isChecked()) {
                cb2.setChecked(false);
            }
            if (cb3.isChecked()) {
                cb3.setChecked(false);
            }
            showRecommendPopwindowView();
        } else {
            if (popupWindow1 != null && popupWindow1.isShowing()) popupWindow1.dismiss();
        }

        if (v.getId() == R.id.cb_2 && cb2.isChecked()) {
            if (cb1.isChecked()) {
                cb1.setChecked(false);
            }
            if (cb3.isChecked()) {
                cb3.setChecked(false);
            }
            showStarPopwindowView();
        } else {
            if (popupWindow2 != null && popupWindow2.isShowing()) popupWindow2.dismiss();
        }

        if (v.getId() == R.id.cb_3 && cb3.isChecked()) {
            if (cb1.isChecked()) {
                cb1.setChecked(false);
            }
            if (cb2.isChecked()) {
                cb2.setChecked(false);
            }
            showComprehensivePopwindowView();
        } else {
            if (popupWindow3 != null && popupWindow3.isShowing()) popupWindow3.dismiss();
        }

        // 推荐排序的点击事件
        // R.id.tv_sort_recommend);
        // R.id.tv_sort_low_price);
        // R.id.tv_hight_price);
        // R.id.tv_praise);
        if (v.getId() == R.id.tv_sort_recommend) {
            orderByStr = "0";
            popupWindow1.dismiss();
            getData();
        } else if (v.getId() == R.id.tv_sort_low_price) {
            orderByStr = "1";
            popupWindow1.dismiss();
            getData();
        } else if (v.getId() == R.id.tv_hight_price) {
            orderByStr = "2";
            popupWindow1.dismiss();
            getData();
        } else if (v.getId() == R.id.tv_praise) {
            orderByStr = "3";
            popupWindow1.dismiss();
            getData();
        }


    }
}
